/*    
 * Copyright 2013 Brandon O'Toole
 * 
 * This file is part of EdgeSleuth.
 *
 * EdgeSleuth is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * EdgeSleuth is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with EdgeSleuth.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.IndieRayDev.EdgeSleuth;

import java.io.OutputStream;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ProgressBar;

public class BilateralFilter extends Activity{
	
	private volatile boolean mRun = true;
	private int mCompleted = 0;
	private FilterThread mThread;
	private Uri mUri;
	private Intent mIntent;
	private Bitmap srcImg;
	
	public class FilterThread extends Thread{
		
		public FilterThread(){
		}
		
		@Override
		public void run(){
			Bitmap result;
			result = computeRow(srcImg, 3);
			
			//prepare the result
			try{
			OutputStream outStream = BilateralFilter.this.getContentResolver().openOutputStream(mUri);
			result.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
			outStream.flush();
			outStream.close();
			setResult(RESULT_OK);
			}
			catch( Exception e)
			{
				setResult(2);
			}
			
			finish();
		}

		private Bitmap computeRow(Bitmap lsrcImg, int lScopeWidth){
				int imageWidth = lsrcImg.getWidth();
				int imageHeight = lsrcImg.getHeight();
				int imageInArray[] = new int[imageWidth * imageHeight];
				int imageFltrArray[] = new int[imageWidth * imageHeight];
				float[] wSums = {0, 0, 0};
				float[] rgb = {0, 0, 0};
				Bitmap lfltrImg;
				
				lfltrImg = Bitmap.createBitmap(lsrcImg.getWidth(), lsrcImg.getHeight(), Bitmap.Config.ARGB_8888);
						
				lsrcImg.getPixels(imageInArray, 0, imageWidth, 0, 0, imageWidth, imageHeight);
				System.arraycopy(imageInArray, 0, imageFltrArray, 0, imageInArray.length);
				final int jEnd = imageHeight - lScopeWidth;
				final int iEnd = imageWidth - lScopeWidth;

				ColorSet scopeColorSet = new ColorSet(lScopeWidth);
				PixelPatch focusSet;
				focusSet = new PixelPatch();
				
				for( int j = lScopeWidth; j<jEnd; j++){
					for( int i = lScopeWidth; i<iEnd; i++){
						if(!mRun) return srcImg;
						focusSet.fillArray(scopeColorSet, imageInArray, i, j, imageWidth, lScopeWidth);
						imageFltrArray[imageWidth*j + i] = oneStepCompute(scopeColorSet, lScopeWidth, rgb, wSums);
					}
					mCompleted = j;
					updateProgress();
				}
				lfltrImg.setPixels(imageFltrArray, 0, lsrcImg.getWidth(), 0, 0, lsrcImg.getWidth(), lsrcImg.getHeight());
				return lfltrImg;
			}

		private int oneStepCompute(ColorSet lColor, int a, float cL[], float[] wSumL){
			final int indEnd = 2*a + 1;
				
			cL[0] = 0;
			cL[1] = 0;
			cL[2] = 0;
			wSumL[0] = 0;
			wSumL[1] = 0;
			wSumL[2] = 0;
				
			int loc;
			final int orig = (a)*(2*a+1) + a;
			
			for(int j = 0; j<indEnd; j++){
				for(int i = 0; i<indEnd; i++){
					loc = j*(2*a+1)+i;
						
					lColor.rW[loc] = computePixelWeight(i, j, lColor.r[loc], lColor.r[orig], a);
					wSumL[0] += lColor.rW[loc];
					cL[0] += lColor.rW[loc] * lColor.r[loc];
					lColor.gW[loc] = computePixelWeight(i, j, lColor.g[loc], lColor.g[orig], a);
					wSumL[1] += lColor.gW[loc];
					cL[1] += lColor.gW[loc] * lColor.g[loc];
					lColor.bW[loc] = computePixelWeight(i, j, lColor.b[loc], lColor.b[orig], a);	
					wSumL[2] += lColor.bW[loc];
					cL[2] += lColor.bW[loc] * lColor.b[loc];
				}
			}
				
			return (	  ( ( (int)(cL[0]/wSumL[0])<<16 ) & 0x00FF0000 ) 
						+ ( ( (int)(cL[1]/wSumL[1])<<8 ) & 0x0000FF00 ) 
						+ ( ( (int)(cL[2]/wSumL[2]) ) & 0xFF )		) 
							| 0xFF000000;
 
		}
					
		private float computePixelWeight(int x, int y, int C, int C0, int patchWidth){
			double rTerm; 
			double cTerm;
			double sigR = 0.10d;
			float sigC = 0.001250f;
			
			rTerm = Math.hypot((int)x-(int)patchWidth, (int)y-(int)patchWidth)*sigR;
			cTerm = ((int)C - (int)C0)*(float)sigC;
			
			return (float)Math.exp( -Math.hypot(rTerm, cTerm) );
		}
	}
	
	static public class ColorSet{
		public int r[], g[], b[];
		public float rW[], gW[], bW[];
		
		public ColorSet(int aIN){
			final int arraySize = (2*aIN + 1)*(2*aIN + 1);
			r = new int[arraySize];
			g = new int[arraySize];
			b = new int[arraySize];
			rW = new float[arraySize];
			gW = new float[arraySize];
			bW = new float[arraySize];
		}
	}
	
	static public class PixelPatch{
		
		public PixelPatch(){
		}
		
		public void fillArray(ColorSet localColors, int[] fillArray, int x, int y, int imageWidth, int scopeSize){
			int lPxColor;
			int loc;
			final int indEnd = 2*scopeSize + 1;
			
			for( int j=0; j<indEnd; j++){
				for( int i=0; i<indEnd; i++){
					loc = j*(2*scopeSize+1) + i;
					lPxColor = fillArray[(y+j-scopeSize)*imageWidth + (x+i-scopeSize)];
					localColors.r[loc] = ( ((lPxColor>>16) & 0xFF) );
					localColors.g[loc] = ( ((lPxColor>>8) & 0xFF));
					localColors.b[loc] = ( ((lPxColor) & 0xFF) );
				}
			}
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bilateralfilter);
		
		ProgressBar progress = (ProgressBar) findViewById(R.id.progressBar2);
		progress.setProgress(mCompleted);
		
		mIntent = getIntent();
		Bundle testBundle = mIntent.getExtras();
		mUri = (Uri)testBundle.get(MediaStore.EXTRA_OUTPUT);
		
		try{
			srcImg = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mUri);
		} 
		catch( Exception e) {
		}
		
		progress.setMax(srcImg.getHeight());
		
		mThread = new FilterThread();
		mThread.start();
	}
	
	private void updateProgress(){
		ProgressBar progress = (ProgressBar) findViewById(R.id.progressBar2);
		progress.setProgress(mCompleted);
	}
	
	public void userCancel(View view){
		mRun = false;
	}
	
	
}
